package com.keyrus.order.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.keyrus.order.pojo.KomsResult;
import com.keyrus.order.pojo.Order;
import com.keyrus.order.repository.KomsOrderRepository;
import com.keyrus.order.service.KomsOrderService;

/**
 * oms订单服务api实现
 *
 * @author David
 * @create 2018-10-23 21:19
 */

@Service
public class KomsOrderServiceImpl implements KomsOrderService
{
    private static final Logger LOG = LogManager.getLogger(KomsOrderServiceImpl.class);

    @Autowired
    private KomsOrderRepository orderRepository;

    /**
     * 传入json创建订单
     * @param orderDTO   订单DTO
     * @return  消息pojo
     */
    @Override
    public KomsResult generateOrder(final Order orderDTO)
    {
        orderDTO.setDate(new Date());

        orderRepository.save(orderDTO);

        final Order saveOrder = orderRepository.findByCode(orderDTO.getCode());
        LOG.info("====================== order info : {}", saveOrder);
        return new KomsResult(true, "订单创建成功", orderDTO);
    }

    /**
     * 查找所有订单
     * @param platform  所属平台
     * @param status    订单状态
     * @return  所有订单list
     */
    @Override
    public KomsResult getAllOrders(final List<String> platform, final List<String> status, final PageRequest pageRequest)
    {
        final List<Order> orders = orderRepository.findOrdersByPlatformInAndStatusIn(platform, status, pageRequest);

        //构造data节点
        final JSONObject data = new JSONObject();
        data.put("items", JSONArray.toJSON(orders));
        data.put("total", orderRepository.findOrdersByPlatformInAndStatusIn(platform, status).size());
        return new KomsResult(true, "查询成功", data);
    }

    /**
     * 根据订单编号查找订单
     * @param code  订单编号
     * @param platform  所属平台
     * @param status    订单状态
     * @return  单个订单
     */
    @Override
    public KomsResult getOrderByCode(final String code, final List<String> platform, final List<String> status)
    {
        //构造data节点
        final Order order = orderRepository.findByCodeAndPlatformInAndStatusIn(code, platform, status);

        if (order == null)
        {
            final JSONObject data = new JSONObject();
            data.put("items", "");
            data.put("total", 0);
            return new KomsResult(false, "查询失败，订单不存在", data);
        }
        else
        {
            final JSONObject data = new JSONObject();
            data.put("items", new JSONArray(){{add(order);}});
            data.put("total", 1);
            return new KomsResult(true, "查询成功", data);
        }
    }
}
